#endcoding:utf-8
class DealsController < ApplicationController
  def create
    ActiveRecord::Base.transaction do
      deal = Deal.new(deal_params)
      deal.save
      demand = Demand.find(params[:demand_id])
      demand.update({:status=>2})
      offer = Offer.find(params[:deal][:offer_id])
      offer.update({:status=>1})
      reciver = offer.user_id
      message = "恭喜你！你中标了！"
      content = message_link message,demand_path(demand)
      send_message(reciver,content,demand.id)
    end
    render :json=>{stat:1}
  end

  def myorders
    @user = userinfo
    @key = isfactory? ? "dm":"o"
    @other = isfactory? ? "o":"dm"
    @demands = User.find_by_sql('select d.*,dm.*,'+@other+'.user_id as other_id from deals as d left join demands dm on dm.id=d.demand_id left join offers o on o.id=d.offer_id where '+@key+'.user_id='+uid+' order by d.created_at desc').paginate :page=> params[:page],:per_page=> 2
  end

  private
  def deal_params
    params.require(:deal).permit(:demand_id,:offer_id)
  end
end
